/**
 * 产品详情
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Row, Col, Tabs, Card, Button, Input, message } from 'antd';
import { detail, create, update } from '../../../services/product';
import { syncDataPoint, dataPointList } from '../../../services/productDataPoint';
import { isSuccess } from '../../../configs/error';
import OperationHistory from '../../../components/operationHistory';
import PermissionControl, { inPermissionList } from '../../../components/permissionControl';
import DeviceTable from '../../device/table';
import DataPointTable from './dataPoint';
import BaseInfo from './baseInfo';
import FeeEditBox from './feeEditBox';
import ControlEditBox from './controlEditBox';
import StatusEditBox from './statusEditBox';
import ReportEditBox from './reportEditBox';
import ThirdConfigurationBox from './thirdConfigurationBox.js';
// import showSecondBread from '../../../components/decorator/showSecondBread';

const TabPane = Tabs.TabPane;

const setting = ['service', 'control', 'status', 'report', 'thirdControl'];

// @showSecondBread('产品详情')
class Detail extends Component {
	constructor(props, context) {
		super(props, context);
		this.id = props.params.id;
		this.state = {
			product: {},
			tab: 'device',
			dataPoints: []
		};
	}

	componentWillMount() {
		this.getDetail();
	}

	componentWillReceiveProps(nextProps) {
		this.id = nextProps.params.id;
		if (nextProps.params.id !== this.props.params.id) {
			this.getDetail();
			if (this.props.params.id === 'new') { // 新增了一个产品
				this.needSync = true;
				this.isNew = true;
			}
		}
	}

	async getDetail() {
		if (this.id !== 'new') {
			const res = await detail(this.id);
			if (isSuccess(res)) {
				this.setProduct(res.data);
			} else {
				throw res;
			}
		}
	}

	setProduct(data) {
		const { product: oldProduct } = this.state;
		const { productDataPoints, ...product } = data;
		const newState = { product: { ...oldProduct, ...product } };
		productDataPoints ? newState.dataPoints = productDataPoints : null;
		this.setState(newState, () => this.needSync ? this.sync() : null);
	}

	tabChange = tab => {
		this.setState({ tab });
	}

	sync = async () => {
		this.needSync = false;
		const { product } = this.state;
		const res = await syncDataPoint({
			gizwitsEnterpriseId: product.gizwitsEnterpriseId,
			gizwitsEnterpriseSecret: product.gizwitsEnterpriseSecret,
			gizwitsProductKey: product.gizwitsProductKey,
			gizwitsProductSecret: product.gizwitsProductSecret,
			productId: product.id
		});
		if (isSuccess(res)) {
			message.success('同步成功');
			this.setProduct({
				...product,
				productDataPoints: res.data.dataPoints
			});
		}
	}

	check = e => {
		// 合进data
		this.dataPointChanged = true;
		const { dataPoints } = this.state;
		const { checked, id } = e.target;
		const newDataPoints = dataPoints.map(d => {
			if (d.id === id) {
				return { ...d, isMonit: checked * 1 };
			} else {
				return d;
			}
		});
		this.setState({ dataPoints: newDataPoints });
	}

	save = async data => {
		const { history, dispatch } = this.props;
		const { dataPoints, product } = this.state;
		let res = null;
		if (this.id !== 'new') {
			// 把数据点也收集起来一起更新
			data.id = this.id;
			this.dataPointChanged ? data.dataPoints = dataPoints.map(d => ({ id: d.id, isMonit: d.isMonit })) : null;
			res = await update(data);
			if (isSuccess(res)) {
				this.dataPointChanged = false;
				message.success('保存成功');
				this.setProduct({ ...product, ...data });
				dispatch({ type: 'productList/query' });
			}
		} else {
			res = await create(data);
			if (isSuccess(res)) {
				history.push(`/productList/${res.data}`);
				message.success('保存成功');
				dispatch({ type: 'productList/query' });
			}
		}
	}

	render() {
		const { product, tab, dataPoints } = this.state;
		const { productList, permissionList } = this.props;
		const rowShow = setting.includes(tab);
		const show = setting.reduce((p, s) => {
			p[s] = s === tab;
			return p;
		}, {});
		return (
			<div className="content-inner">
				<BaseInfo data={product} save={this.save} isNew={this.isNew} list={productList.list} mode={this.id} />
				{
					product.id ? <Tabs defaultActiveKey={tab} onChange={this.tabChange} animated={false}>
                {
							inPermissionList(permissionList, [


								{ url: '/report_data', com: <TabPane tab="设备上报" key="report" /> },

							])
						}
					</Tabs> : null
				}
				{
					product.id ? <Row gutter={16} style={{ display: rowShow ? 'block' : 'none' }}>
						<Col span={12}>
							<DataPointTable
								dataSource={dataPoints}
								onSync={this.sync}
								onCheck={this.check}
							/>
						</Col>
						<Col span={12}>
							<PermissionControl
								url="/service_mode"
								children={
									<FeeEditBox
										show={show.service}
										dataPoint={dataPoints}
										productId={product.id}
									/>}
							/>
							<PermissionControl
								url="/control_command"
								children={
									<ControlEditBox
										show={show.control}
										dataPoint={dataPoints}
										productId={product.id}
									/>}
							/>
							<PermissionControl
								url="/status_command"
								children={
									<StatusEditBox
										show={show.status}
										dataPoint={dataPoints}
										productId={product.id}
									/>}
							/>
							<PermissionControl
								url="/report_data"
								children={
									<ReportEditBox
										show={show.report}
										dataPoint={dataPoints}
										productId={product.id}
									/>}
							/>
							<PermissionControl
								url="/sys/setting"
								children={
									<ThirdConfigurationBox
										show={show.thirdControl}
										dataPoint={dataPoints}
										productId={product.id}
										productId={product.id}
									/>}
							/>
						</Col>
					</Row> : null
				}
			</div>
		);
	}
}

Detail.propTypes = {

};

export default connect(({ productList, app }) => ({ productList, permissionList: app.user.permissions }))(Detail);
